﻿using MediatR;
using T.Vehicleservice.Domain.Dtos;
using T.Vehicleservice.Domain.T.MaintenanceRecord.Model;
using T.Vehicleservice.Domain.T.ViolationRecords.Model;
using T.Vehicleservice.Read.API.Application.Command.ViolationRecordCommand;
using T.Vehicleservice.Repository.ImpI;
using T.Vehicleservice.Repository.Interface;

namespace T.Vehicleservice.Read.API.Application.CommandHandlers.ViolationRecordCommandHander
{
    /// <summary>
    /// 显示违章信息
    /// </summary>
    public class ViolationRecordListCommandHander : IRequestHandler<ViolationRecordListCommand, PageDto<ViolationRecord>>
    {
        private readonly IViolationRecordRepository _violationRecordRepository;
        public ViolationRecordListCommandHander(IViolationRecordRepository violationRecordRepository)
        {
            _violationRecordRepository = violationRecordRepository;
        }
        public async Task<PageDto<ViolationRecord>> Handle(ViolationRecordListCommand request, CancellationToken cancellationToken)
        {
            PageDto<ViolationRecord> pageDto = new PageDto<ViolationRecord>();
            var ViolationRecordList = await _violationRecordRepository.GetAsync(d => !d.IsDeleted);
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                ViolationRecordList = ViolationRecordList.Where(d => d.CompanyID == request.CompanyID).ToList();
            }
            if (!string.IsNullOrEmpty(request.ViolationTitle))
            {
                ViolationRecordList = ViolationRecordList.Where(d => d.ViolationTitle.Contains(request.ViolationTitle)).ToList();
            }
            if (request.ViolationDate != null)
            {
                ViolationRecordList = ViolationRecordList.Where(d => d.ViolationDate == request.ViolationDate).ToList();
            }
            if (!string.IsNullOrEmpty(request.LicensePlateNumber))
            {
                ViolationRecordList = ViolationRecordList.Where(d => d.LicensePlateNumber.Contains(request.LicensePlateNumber)).ToList();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = ViolationRecordList.Count();
            }
            var size = request.PageSize;
            var index = request.PageIndex;
            pageDto.TotalCount = ViolationRecordList.Count();
            pageDto.PageCount = (int)Math.Ceiling(pageDto.PageCount * 1.0 / (int)size);
            pageDto.list = ViolationRecordList.OrderByDescending(d => d.CreatedDate).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return pageDto;
        }
    }
}
